package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnTextChanged;
import butterknife.Unbinder;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CompleteMessage;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataFlg;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.EnterpriseList;
import com.isunland.managesystem.entity.RProInvoiceRecd;
import com.isunland.managesystem.entity.RProInvoiceRecdSub;
import com.isunland.managesystem.entity.ReceiptDetailLab;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.NumberUtil;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineViewNew;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能: 开票信息
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2016/11/30 10:30
 */

public class ReceiptInfoFragment extends BaseFragment implements View.OnClickListener {
  public static final String EXTRA_RECEIPT = "com.isunland.managesystem.ui.EXTRA_RECEIPT";
  public static final String EXTRA_SALES_TAX =
      "com.isunland.managesystem.ui.ReceiptInfoFragment.SALES_TAX";
  public static final String EXTRA_SALES_MONEY =
      "com.isunland.managesystem.ui.ReceiptInfoFragment.SALES_MONEY";
  public static final String EXTRA_SUM_MONEY =
      "com.isunland.managesystem.ui.ReceiptInfoFragment.SUM_MONEY";
  protected static final int ADD = 1;// 添加
  protected static final int EDIT = 2;// 修改
  protected static final int WAIT_CHECK = 3;// 审核中
  protected static final int CHECK_PASS = 4;// 已审核
  protected static final int START = 1;
  protected static final int SAVE = 0;
  //    protected static final int SAVE_AFTER_CHILD = 2;// 子表保存后再次保存主表
  private static final int REQUEST_SUBMIT = 1;
  private static final int REQUEST_DELETE = 2;
  private static final int REQUEST_ENTERPRISE = 3;
  private static final int REQUEST_RECEIPT_TYPE = 4;// 开票类别
  private static final int REQUEST_CONTRACT = 5;// 合同.
  private static final int REQUEST_START = 6;
  private static final int REQUEST_DATA = 7;//开票时间
  private static final int REQUEST_DETAIL = 8;
  private static final int REQUEST_DEADLINE = 9;//开票截止日期
  private static final int REQUEST_RECEIVE_DATE = 10;//收票日期
  private static final int REQUEST_RECEIVE_PERSON = 11;//收票人
  private static final int REQUEST_RECEIPT_PERSON = 12;//开票人
  protected RProInvoiceRecd mReceiptDetail;
  protected int mMenuType;
  @BindView(R.id.tv_unitName_receiptInfo) SingleLineViewNew mUnitNameTv;
  @BindView(R.id.et_taxPayerNo_receiptInfo) SingleLineViewNew mTaxpayerNoEt;
  @BindView(R.id.et_openingBank_receiptInfo) SingleLineViewNew mOpeningBankEt;
  @BindView(R.id.et_address_receiptInfo) SingleLineViewNew mAddressEt;
  @BindView(R.id.et_phone_receiptInfo) SingleLineViewNew mPhoneEt;
  @BindView(R.id.et_account_receiptInfo) SingleLineViewNew mAccountEt;
  @BindView(R.id.tv_contractBill_receiptInfo) SingleLineViewNew mContractBillEt;
  @BindView(R.id.et_contractAccount_receiptInfo) SingleLineViewNew mContractAccountEt;
  @BindView(R.id.et_affairContent_receiptInfo) SingleLineViewNew mAffairContentEt;
  @BindView(R.id.et_customerReponsible_receiptInfo) SingleLineViewNew mCustomerReponsibleEt;
  @BindView(R.id.et_receiptType_receiptInfo) SingleLineViewNew mReceiptTypeTv;
  @BindView(R.id.et_remarks_receiptInfo) SingleLineViewNew mRemarksEt;

  @BindView(R.id.et_taxTotal_receiptInfo) EditText mTaxTotalEt;
  @BindView(R.id.et_taxTotalCapitalization_receiptInfo) EditText mTaxTotalCapEt;

  @BindView(R.id.et_receiptNumber_receiptInfo) SingleLineViewNew mReceiptNumberEt;//发票编号
  @BindView(R.id.et_receiptTime_receiptInfo) SingleLineViewNew mReceiptTimeEt;
  @BindView(R.id.et_receiptPerson_receiptInfo) SingleLineViewNew mReceiptPersonEt;//开票人
  @BindView(R.id.et_registerPerson_receiptInfo) SingleLineViewNew mRegisterPersonEt;//收票人
  @BindView(R.id.et_registerTime_receiptInfo) SingleLineViewNew mRegisterTimeEt;
  @BindView(R.id.et_dataStatus_receiptInfo) SingleLineViewNew mDataStatusEt;
  @BindView(R.id.et_salesTax_receiptInfo) SingleLineViewNew mSalesTaxEt;// 销项税
  @BindView(R.id.et_salesMoney_receiptInfo) SingleLineViewNew mSalesMoneyEt;// 销项额
  @BindView(R.id.et_outReceiptUnit_receiptInfo) SingleLineViewNew mOutReceiptUnitEt;// 开票单位.
  @BindView(R.id.et_receiptDeadline_receiptInfo) SingleLineViewNew etReceiptDeadlineReceiptInfo;
  //开票截止日期
  @BindView(R.id.et_receiptDeliveryDate_receiptInfo) SingleLineViewNew
      etReceiptDeliveryDateReceiptInfo;
  //票交付日期
  @BindView(R.id.et_receivePerson_receiptInfo) SingleLineViewNew etReceivePersonReceiptInfo;//收票人
  @BindView(R.id.et_payWayDescribe_receiptInfo) SingleLineViewNew etPayWayDescribeReceiptInfo;
  //交付方式及说明
  @BindView(R.id.tv_goodsDetail_receiptInfo) TextView tvGoodsDetailReceiptInfo;//货品明细
  //    private Callbacks mCallbacks;
  private Unbinder unbinder;

  public static ReceiptInfoFragment newInstance(RProInvoiceRecd receptDetail) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_RECEIPT, receptDetail);
    ReceiptInfoFragment fragment = new ReceiptInfoFragment();
    fragment.setArguments(args);
    return fragment;
  }

  //    @Override
  //    public void onAttach(Activity activity) {
  //        super.onAttach(activity);
  //        mCallbacks = (Callbacks) activity;
  //    }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.enterprise_receipt_register);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_receipt_info, container, false);
    unbinder = ButterKnife.bind(this, v);
    initData();
    return v;
  }

  @Override public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
  }

  //    @Override
  //    public void onDetach() {
  //        super.onDetach();
  //        mCallbacks = null;
  //    }

  @SuppressWarnings("deprecation") @Override
  public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    mReceiptDetail = (RProInvoiceRecd) getArguments().getSerializable(EXTRA_RECEIPT);

    mAffairContentEt.getTvContent().setHint(R.string.completeMust);
    mCustomerReponsibleEt.getTvContent().setHint(R.string.completeMust);
    mReceiptTypeTv.getTvContent().setHint(R.string.chooseMust);
    if (mReceiptDetail == null) {
      // 添加
      mMenuType = ADD;
    } else {
      // 其他
      String dataStattus = mReceiptDetail.getDataStatus();
      if (dataStattus.equals(DataStatus.WAIT_CHECK)) {
        mMenuType = WAIT_CHECK;
      }
      if (dataStattus.equals(DataStatus.CHECK_PASS)) {
        mMenuType = CHECK_PASS;
      }
      if (dataStattus.equals(DataStatus.ABORT) || dataStattus.equals(DataStatus.NEW)) {
        mMenuType = EDIT;
      }
    }
    // 如果不是添加,都有值.
    if (mMenuType != ADD) {
      // 主记录id,合同订单id,合同订单类型.用于动态生成子表.
      SharedPreferencesUtil.setString(getActivity(), SharedPreferencesUtil.RECEIPT_ID,
          mReceiptDetail.getId());
      SharedPreferencesUtil.setString(getActivity(), SharedPreferencesUtil.RECEIPT_CONTRACT_ID,
          mReceiptDetail.getContractBillId());
      SharedPreferencesUtil.setString(getActivity(), SharedPreferencesUtil.RECEIPT_CONTRACT_TYPE,
          mReceiptDetail.getOrderType());

      mUnitNameTv.setTextContent(mReceiptDetail.getCustomerName());
      mTaxpayerNoEt.setTextContent(mReceiptDetail.getTaxAccount());
      mOpeningBankEt.setTextContent(mReceiptDetail.getBank());
      mAddressEt.setTextContent(mReceiptDetail.getAddress());
      mPhoneEt.setTextContent(mReceiptDetail.getPhone());
      mAccountEt.setTextContent(mReceiptDetail.getBankAccount());
      mContractBillEt.setTextContent(mReceiptDetail.getContractBillName());
      mAffairContentEt.setTextContent(mReceiptDetail.getContent());
      mCustomerReponsibleEt.setTextContent(mReceiptDetail.getCustomerHandleName());
      mReceiptTypeTv.setTextContent(mReceiptDetail.getInvoiceName());
      mRemarksEt.setTextContent(mReceiptDetail.getRemark());
      mContractAccountEt.setTextContent(mReceiptDetail.getContractAmount() + "");
      mTaxTotalEt.setText(NumberUtil.numberBigToString(mReceiptDetail.getMakedInvoiceAmount()));
      mTaxTotalCapEt.setText(
          NumberUtil.number2CNMontrayUnit(mReceiptDetail.getMakedInvoiceAmount()));
      mReceiptNumberEt.setTextContent(mReceiptDetail.getInvoiceNumber());
      mReceiptTimeEt.setTextContent(mReceiptDetail.getOccurDate());
      mReceiptPersonEt.setTextContent(mReceiptDetail.getInvoiceMaker());
      mRegisterPersonEt.setTextContent(mReceiptDetail.getRegStaffName());
      mRegisterTimeEt.setTextContent(mReceiptDetail.getRegDate());
      mDataStatusEt.setTextContent(DataStatus.getDataStatusName(mReceiptDetail.getDataStatus()));

      mSalesTaxEt.setTextContent(NumberUtil.numberBigToString(mReceiptDetail.getOutputTax()));
      mSalesMoneyEt.setTextContent(NumberUtil.numberBigToString(mReceiptDetail.getMtsumPrice()));
      mOutReceiptUnitEt.setTextContent(mReceiptDetail.getInvoiceDeptName());
      etReceiptDeadlineReceiptInfo.setTextContent(mReceiptDetail.getInvoiceDeadline());
      etReceiptDeliveryDateReceiptInfo.setTextContent(mReceiptDetail.getInvoiceReciveDate());
      etReceivePersonReceiptInfo.setTextContent(mReceiptDetail.getInvoiceReciverName());
      etPayWayDescribeReceiptInfo.setTextContent(mReceiptDetail.getInvoiceReciveDesc());
    } else {
      // 添加,初始化数据.
      mReceiptDetail = new RProInvoiceRecd();
      // id
      String id = UUID.randomUUID().toString();
      mReceiptDetail.setId(id);
      // 主记录id,合同订单id,合同订单类型.用于动态生成子表.
      SharedPreferencesUtil.setString(getActivity(), SharedPreferencesUtil.RECEIPT_ID,
          mReceiptDetail.getId());
      SharedPreferencesUtil.setString(getActivity(), SharedPreferencesUtil.RECEIPT_CONTRACT_ID, "");
      // 数据状态.
      mDataStatusEt.setTextContent(DataStatus.getDataStatusName(DataStatus.NEW));
      mReceiptDetail.setDataStatus(DataStatus.NEW);
      // 申请人
      mRegisterPersonEt.setTextContent(mCurrentUser.getRealName());
      // 申请时间.
      mReceiptDetail.setRegDate(MyDateUtil.dateToString(new Date()));
      mRegisterTimeEt.setTextContent(MyDateUtil.dateToString(new Date()));
      // memberCode
      mReceiptDetail.setMemberCode(mCurrentUser.getMemberCode());
      // 开票.
      mReceiptDetail.setInvoiceKind("out");
      // 开票单位.
      mReceiptDetail.setInvoiceDeptName(mCurrentUser.getMemberName());
      mOutReceiptUnitEt.setTextContent(mReceiptDetail.getInvoiceDeptName());
    }
    // 设置 价税合计是否可编辑
    enableTaxTotal();
    tvGoodsDetailReceiptInfo.setTag(tvGoodsDetailReceiptInfo.getId());
    tvGoodsDetailReceiptInfo.setOnClickListener(this);
    mUnitNameTv.setOnClickContentListener(this);
    mContractBillEt.setOnClickContentListener(this);
    mReceiptTypeTv.setOnClickContentListener(this);
    mReceiptTimeEt.setOnClickContentListener(this);
    etReceiptDeadlineReceiptInfo.setOnClickContentListener(this);
    etReceiptDeliveryDateReceiptInfo.setOnClickContentListener(this);
    mReceiptPersonEt.setOnClickContentListener(this);
    etReceivePersonReceiptInfo.setOnClickContentListener(this);

    // 如果是审核通过,或正在审核状态不可以修改.
    if (mMenuType == CHECK_PASS || mMenuType == WAIT_CHECK) {
      mUnitNameTv.setEnabled(false);
      mTaxpayerNoEt.setEnabled(false);
      mOpeningBankEt.setEnabled(false);
      mAddressEt.setEnabled(false);
      mPhoneEt.setEnabled(false);
      mAccountEt.setEnabled(false);
      mContractBillEt.setEnabled(false);
      mContractAccountEt.setEnabled(false);
      mAffairContentEt.setEnabled(false);
      mCustomerReponsibleEt.setEnabled(false);
      mReceiptTypeTv.setEnabled(false);
      mRemarksEt.setEnabled(false);
      mTaxTotalEt.setEnabled(false);
      mTaxTotalCapEt.setEnabled(false);
      mReceiptNumberEt.setEnabled(false);
      mReceiptTimeEt.setEnabled(false);
      mReceiptPersonEt.setEnabled(false);
      mRegisterPersonEt.setEnabled(false);
      mRegisterTimeEt.setEnabled(false);
      mDataStatusEt.setEnabled(false);
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (mMenuType) {
      case ADD:
        inflater.inflate(R.menu.menu_save_submit_delete_goodsdetail, menu);
        //添加时隐藏删除按钮.
        menu.getItem(3).setVisible(false);
        break;
      case EDIT:
        inflater.inflate(R.menu.menu_save_submit_delete_goodsdetail, menu);

        break;
      case WAIT_CHECK:
        inflater.inflate(R.menu.menu_stop_goodsdetail, menu);
        break;
      case CHECK_PASS:
        inflater.inflate(R.menu.menu_stop_goodsdetail, menu);
        menu.getItem(1).setVisible(false);
        break;

      default:
        break;
    }

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:

        if (ReceiptDetailLab.get(getActivity()).isUnsaved()) {

          new AlertDialog.Builder(getActivity()).setTitle(R.string.hintMessage)
              .setMessage(R.string.isSaveChildForm)
              .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {

                @Override public void onClick(DialogInterface dialog, int which) {
                  volleyPostSaveChildForm();
                }
              })
              .setNegativeButton(R.string.notSave, new DialogInterface.OnClickListener() {

                @Override public void onClick(DialogInterface dialog, int which) {

                  getActivity().finish();
                }
              })
              .create()
              .show();
        } else {
          if (NavUtils.getParentActivityName(getActivity()) != null) {
            NavUtils.navigateUpFromSameTask(getActivity());
          }
        }
        return true;
      //添加子表
      case R.id.menu_item_add:
        turnToDetail();

        break;
      // 保存
      case R.id.menu_item_save:
        //                boolean isCorrect = isCorrectInput();
        //                if (isCorrect) {

        volleyPostInvoiceUnique(SAVE);
        //                }
        // ToastUtil.show("保存");
        break;
      // 启动流程
      case R.id.menu_item_submit:
        boolean isCorrectSubmit = isCorrectInput();
        if (isCorrectSubmit) {

          volleyPostInvoiceUnique(START);
        }

        break;
      // 删除.
      case R.id.menu_item_delete:
        showDialog(REQUEST_DELETE);
        break;

      // 终止流程
      case R.id.menu_item_stop:
        volleyPostStop();
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 跳转到子表
   */
  private void turnToDetail() {
    Intent intent = new Intent(getActivity(), ReceiptDetailListActivity.class);
    intent.putExtra(ReceiptInfoFragment.EXTRA_RECEIPT, mReceiptDetail);
    startActivityForResult(intent, REQUEST_DETAIL);
  }

  /**
   * 保存子表数据.
   */
  private void volleyPostSaveChildForm() {

    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RECEIPT_DETAIL_SAVE);
    HashMap<String, String> params = new HashMap<>();
    String json = new Gson().toJson(ReceiptDetailLab.get(getActivity()).getList());
    params.put("json", json);

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();
          if (successType.equals("1")) {
            ReceiptDetailLab.get(getActivity()).setUnsaved(false);
            ToastUtil.show(R.string.save_success);
            // 保存成功后跳转到主表.
            turnToMain();
          } else {
            ToastUtil.show(R.string.save_failure);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.save_failure);
        }
      }

      private void turnToMain() {
        Double salestax = 0.0;
        Double salesMoney = 0.0;
        Double sumMoney = 0.0;
        for (RProInvoiceRecdSub item : ReceiptDetailLab.get(getActivity()).getList()) {
          // 销项额
          // protected Double mtsumPrice;
          // 销项税
          // protected Double outputTax;
          salestax += item.getOutputTax();
          salesMoney += item.getMtsumPrice();
          // 价税合计
          sumMoney = item.getMsumPrice();
        }

        updateSalesTaxMoney(salestax, salesMoney, sumMoney);
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("VolleyError", arg0);
        ToastUtil.show(R.string.save_failure);
      }
    });
  }

  /**
   * 启动流程接口
   */
  private void volleypostStart() {

    MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RECEIPT_START);
    HashMap<String, String> params = new HashMap<>();

    params.put("id", mReceiptDetail.getId());
    params.put("dataStatus", mReceiptDetail.getDataStatus());
    params.put("invoiceKind", "out");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();
          if (successType.equals("1")) {
            ToastUtil.show(R.string.submit_success);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.submit_failure);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.submit_failure);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("VolleyError", arg0);
        ToastUtil.show(R.string.submit_failure);
      }
    });
  }

  /**
   * 验证发票编号是否唯一.
   * 唯一的时候调用保存启动流程接口,不唯一提示用户
   *
   * @param type 保存或启动流程.
   */
  private void volleyPostInvoiceUnique(final int type) {
    //开票单位必填,网页端是必填但是没限制.统一吧.
    //if (MyStringUtil.isEmptyTextView(mUnitNameTv.getTvContent())) {
    //  ToastUtil.show("请填写开票单位");
    //  return;
    //}

    //验证唯一性.
    MyUtils.showDialogLoading(getActivity(), R.string.loadingInvoice);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_INVOICE_UNIQUE);
    HashMap<String, String> params = new HashMap<>();
    params.put("validId", mReceiptDetail.getId());//主记录id
    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    params.put("invoiceNumber", mReceiptNumberEt.getTextContent());//发票编号

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();

        CompleteMessage completeMessage = new Gson().fromJson(arg0, CompleteMessage.class);

        if (completeMessage.getResult() == CompleteMessage.SUCCESS) {
          //发票是唯一的,可以调用保存接口.
          volleypostSave(type);
        } else {
          ToastUtil.show(completeMessage.getMessage());
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("VolleyError", arg0);
        ToastUtil.show("无法验证发票唯一性,保存失败");
      }
    });
  }

  /**
   * 保存
   * 先验证发票编号是否唯一.
   * 启动流程时先调用保存接口,再调用启动流程接口.
   *
   * @param type 保存或启动流程.
   */
  private void volleypostSave(final int type) {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RECEIPT_SAVE);
    HashMap<String, String> params = new HashMap<>();

    mReceiptDetail.setCustomerName(mUnitNameTv.getTextContent());
    mReceiptDetail.setTaxAccount(mTaxpayerNoEt.getTextContent());
    mReceiptDetail.setBank(mOpeningBankEt.getTextContent());
    mReceiptDetail.setAddress(mAddressEt.getTextContent());
    mReceiptDetail.setPhone(mPhoneEt.getTextContent());
    mReceiptDetail.setBankAccount(mAccountEt.getTextContent());
    mReceiptDetail.setContractBillName(mContractBillEt.getTextContent());
    Double contractAmount;
    try {
      contractAmount = Double.parseDouble(mContractAccountEt.getTextContent());
    } catch (NumberFormatException e1) {
      e1.printStackTrace();
      contractAmount = 0.0;
    }
    Double invoiceAmount;
    try {
      invoiceAmount = Double.parseDouble(mTaxTotalEt.getText().toString().trim());
    } catch (NumberFormatException e1) {
      invoiceAmount = 0.0;
      e1.printStackTrace();
    }
    mReceiptDetail.setContractAmount(contractAmount);
    mReceiptDetail.setMakedInvoiceAmount(invoiceAmount);
    mReceiptDetail.setContent(mAffairContentEt.getTextContent());
    mReceiptDetail.setCustomerHandleName(mCustomerReponsibleEt.getTextContent());
    mReceiptDetail.setRemark(mRemarksEt.getTextContent());

    mReceiptDetail.setInvoiceNumber(mReceiptNumberEt.getTextContent());
    mReceiptDetail.setOccurDate(mReceiptTimeEt.getTextContent());
    mReceiptDetail.setRegStaffName(mRegisterPersonEt.getTextContent());
    mReceiptDetail.setRegDate(mRegisterTimeEt.getTextContent());

    mReceiptDetail.setInvoiceDeadline(etReceiptDeadlineReceiptInfo.getTextContent());
    mReceiptDetail.setInvoiceReciveDate(etReceiptDeliveryDateReceiptInfo.getTextContent());
    //开票人,收票人改为选择的,在选择时赋值.
    //mReceiptDetail.setInvoiceMaker(mReceiptPersonEt.getText().toString().trim());
    //mReceiptDetail.setInvoiceReciverName(etReceivePersonReceiptInfo.getText().toString().trim());

    mReceiptDetail.setInvoiceReciveDesc(etPayWayDescribeReceiptInfo.getTextContent());

    String json = new Gson().toJson(mReceiptDetail);
    params.put("json", json);

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();
          if (successType.equals("1")) {
            getActivity().setResult(Activity.RESULT_OK);
            ToastUtil.show(R.string.save_success);

            // 保存成功,如果需要启动流程,弹出提示框.
            if (type == START) {
              showDialog(REQUEST_START);
            }
            // 新建保存成功后时跳转到子表.修改不行,因为
            //                        if (type == SAVE) {
            ////                            mCallbacks.skip();
            //                        }
            // 子表保存成功后,将再次保存主表,再次保存成功后关闭页面.
            //                        if (type == SAVE_AFTER_CHILD) {
            //
            //                            getActivity().finish();
            //                        }

          } else {
            ToastUtil.show(R.string.save_failure);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.save_failure);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("VolleyError", arg0);
        ToastUtil.show(R.string.save_failure);
      }
    });
  }

  private boolean isCorrectInput() {

    //		String unitName = mUnitNameTv.getText().toString().trim();
    //		if (TextUtils.isEmpty(unitName)) {
    //			ToastUtil.showEmpty(R.string.unitName);
    //
    //			return false;
    //		}
    //		String number = mTaxpayerNoEt.getText().toString().trim();
    //		if (TextUtils.isEmpty(number)) {
    //			ToastUtil.showEmpty(R.string.taxPayerNo);
    //			return false;
    //		}
    //相关合同非必填,保存和启动流程时.
    //		 String contractBill = mContractBillEt.getText().toString().trim();
    //		 if (TextUtils.isEmpty(contractBill)) {
    //
    //		 ToastUtil.showEmpty(R.string.contractBill);
    //		 return false;
    //		 }
    String content = mAffairContentEt.getTextContent();
    if (TextUtils.isEmpty(content)) {

      ToastUtil.showEmpty(R.string.affairContent);
      return false;
    }
    String person = mCustomerReponsibleEt.getTextContent();
    if (TextUtils.isEmpty(person)) {

      ToastUtil.showEmpty(R.string.customerContact);
      return false;
    }
    String type = mReceiptTypeTv.getTextContent();
    if (TextUtils.isEmpty(type)) {
      ToastUtil.showEmpty(R.string.receiptType);

      return false;
    }

    //       if (mReceiptDetail.getMakedInvoiceAmount()==null||mReceiptDetail.getMakedInvoiceAmount()==0){
    //           ToastUtil.show(mActivity.getString(R.string.hint_total_tax_empty));
    //           return false;
    //       }
    return true;
  }

  @OnTextChanged(R.id.et_taxTotal_receiptInfo) public void onTextChanged(CharSequence s) {

    String text = s.toString();
    if (TextUtils.isEmpty(text)) {
      mReceiptDetail.setMakedInvoiceAmount(0.0);

      mTaxTotalCapEt.setText("");
      return;
    }

    try {
      Double amount = Double.parseDouble(text);
      mReceiptDetail.setMakedInvoiceAmount(amount);

      mTaxTotalCapEt.setText(NumberUtil.number2CNMontrayUnit(amount));
    } catch (NumberFormatException e) {
      e.printStackTrace();
      mReceiptDetail.setMakedInvoiceAmount(0.0);

      mTaxTotalCapEt.setText("");
    }
  }

  @Override public void onClick(View view) {
    if (!(view.getTag() instanceof Integer)) return;
    int id = (int) view.getTag();
    switch (id) {
      case R.id.tv_goodsDetail_receiptInfo:
        turnToDetail();

        break;
      case R.id.tv_unitName_receiptInfo:
        Intent intent = new Intent(getActivity(), EnterprisePagerActivity.class);
        startActivityForResult(intent, REQUEST_ENTERPRISE);

        break;
      case R.id.tv_contractBill_receiptInfo:
        if (TextUtils.isEmpty(mReceiptDetail.getCustomerId())) {
          ToastUtil.show(R.string.noCustomerOrSupplier);
          return;
        }

        Intent intent2 = new Intent(getActivity(), ContractPagerActivity.class);
        intent2.putExtra(ContractPagerActivity.EXTRA_CUSTOMER_ID, mReceiptDetail.getCustomerId());
        startActivityForResult(intent2, REQUEST_CONTRACT);

        break;
      case R.id.et_receiptType_receiptInfo:// 开票类别
        showDialog(REQUEST_RECEIPT_TYPE);

        break;
      case R.id.et_receiptTime_receiptInfo:// 开票时间
        showDialog(REQUEST_DATA);

        break;
      case R.id.et_receiptDeadline_receiptInfo://
        showDialog(REQUEST_DEADLINE);

        break;
      case R.id.et_receivePerson_receiptInfo://收票人

        startActivityForResult(new Intent(getActivity(), AppointerListActivity.class),
            REQUEST_RECEIVE_PERSON);

        break;
      case R.id.et_receiptPerson_receiptInfo://开票人
        startActivityForResult(new Intent(getActivity(), AppointerListActivity.class),
            REQUEST_RECEIPT_PERSON);

        break;
      case R.id.et_receiptDeliveryDate_receiptInfo://
        showDialog(REQUEST_RECEIVE_DATE);

        break;
      default:
        break;
    }
  }

  /**
   * TODO终止流程
   */
  private void volleyPostStop() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();

    params.put("runId", mReceiptDetail.getRunId() + "");

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();
          if (successType.equals("1")) {
            ToastUtil.show(R.string.interruptSuccess);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.interruptFail);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.interruptFail);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("VolleyError", arg0);
        ToastUtil.show(R.string.failure_operation);
      }
    });
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RECEIPT_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mReceiptDetail.getId());
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            getActivity().setResult(Activity.RESULT_OK);
            ToastUtil.show(R.string.success_operation);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  private void showDialog(int type) {
    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (type) {
      case REQUEST_SUBMIT:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.start_up_hint);
        break;
      case REQUEST_DELETE:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        break;
      case REQUEST_START:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.start_up_hint);
        break;
      case REQUEST_RECEIPT_TYPE:
        dialog = DataDictDialogFragment.newInstance(DataFlg.RECEIPT_TYPE);
        break;
      //开票时间
      case REQUEST_DATA:
        dialog = new BaseYMDTimeDialogFragment();
        break;
      case REQUEST_DEADLINE:
        dialog = new BaseYMDTimeDialogFragment();
        break;
      case REQUEST_RECEIVE_DATE:
        dialog = new BaseYMDTimeDialogFragment();
        break;
      default:
        return;
    }
    dialog.setTargetFragment(this, type);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    //子表保存成功后,更新主表数据.
    if (requestCode == REQUEST_DETAIL) {
      double salestax = data.getDoubleExtra(EXTRA_SALES_TAX, 0);
      double salesMoney = data.getDoubleExtra(EXTRA_SALES_MONEY, 0);
      double sumMoney = data.getDoubleExtra(EXTRA_SUM_MONEY, 0);
      updateSalesTaxMoney(salestax, salesMoney, sumMoney);
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_START) {
      volleypostStart();
    }
    //开票时间
    if (requestCode == REQUEST_DATA) {
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String receipDate = DateUtil.dateToString(date, DateUtil.TYPE_DATE);
      mReceiptTimeEt.setTextContent(receipDate);
    }
    if (requestCode == REQUEST_DEADLINE) {
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String dateStr = DateUtil.dateToString(date, DateUtil.TYPE_DATE);
      etReceiptDeadlineReceiptInfo.setTextContent(dateStr);
    }
    if (requestCode == REQUEST_RECEIVE_DATE) {
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String dateStr = DateUtil.dateToString(date, DateUtil.TYPE_DATE);
      etReceiptDeliveryDateReceiptInfo.setTextContent(dateStr);
    }
    if (requestCode == REQUEST_RECEIPT_TYPE) {
      CustomerDialog dataStatus =
          (CustomerDialog) data.getSerializableExtra(CustomerDialogFragment.EXTRA_VALUE);
      mReceiptDetail.setInvoiceType(dataStatus.getId());
      mReceiptTypeTv.setTextContent(dataStatus.getName());
      // mQuery.setDataStatusKey(dataStatus.getId());
      // mQuery.setDataStatusValue(dataStatus.getName());

    }
    if (requestCode == REQUEST_ENTERPRISE) {
      EnterpriseList item =
          (EnterpriseList) data.getSerializableExtra(EnterpriseListFragment.EXTRA_ENTERPRISE);
      mReceiptDetail.setCustomerId(item.getId());
      mReceiptDetail.setCustomerName(item.getEnterpriseName());
      mReceiptDetail.setCustomerType(item.getCustomerType());
      mUnitNameTv.setTextContent(item.getEnterpriseName());

      String info = item.getAccBankInfo();
      if (info != null && !info.equals("")) {
        try {
          String[] detail = info.split(",");
          // 开户行
          mOpeningBankEt.setTextContent(detail[0]);
          mReceiptDetail.setBank(detail[0]);
          // 银行账号
          mAccountEt.setTextContent(detail[2]);
          mReceiptDetail.setBankAccount(detail[2]);
          // 纳税人识别号.
          mTaxpayerNoEt.setTextContent(detail[3]);
          mReceiptDetail.setTaxAccount(detail[3]);
          // 地址
          mAddressEt.setTextContent(detail[4]);
          mReceiptDetail.setAddress(detail[4]);
          // 联系电话
          // 由于最后一个如果为空的话,split方法会过滤掉,这里要加判断,防止数组下标越界.

          mPhoneEt.setTextContent(detail[5]);
          mReceiptDetail.setPhone(detail[5]);
        } catch (Exception e) {
          // Auto-generated catch block
          e.printStackTrace();
        }
      } else {
        //信息为空,清空显示信息
        // 开户行
        mOpeningBankEt.setTextContent("");
        mReceiptDetail.setBank("");
        // 银行账号
        mAccountEt.setTextContent("");
        mReceiptDetail.setBankAccount("");
        // 纳税人识别号.
        mTaxpayerNoEt.setTextContent("");
        mReceiptDetail.setTaxAccount("");
        // 地址
        mAddressEt.setTextContent("");
        mReceiptDetail.setAddress("");
        // 联系电话
        // 由于最后一个如果为空的话,split方法会过滤掉,这里要加判断,防止数组下标越界.

        mPhoneEt.setTextContent("");
        mReceiptDetail.setPhone("");
      }
    }

    if (requestCode == REQUEST_CONTRACT) {
      RProInvoiceRecd item =
          (RProInvoiceRecd) data.getSerializableExtra(ContractPagerActivity.EXTRA_UPDATE_CONTRACT);
      // 更新数据.清空之前的选择.更新为新的选择.
      mReceiptDetail.setOrderType(item.getOrderType());

      mReceiptDetail.setContractId(item.getContractId());
      mReceiptDetail.setContractName(item.getContractName());
      mReceiptDetail.setContractCode(item.getContractCode());
      mReceiptDetail.setContractAmount(item.getContractAmount());

      mReceiptDetail.setMakedInvoiceAmount(item.getMakedInvoiceAmount());

      mReceiptDetail.setOrderId(item.getOrderId());
      mReceiptDetail.setOrderName(item.getOrderName());

      mReceiptDetail.setProjectId(item.getProjectId());
      mReceiptDetail.setProjectName(item.getProjectName());

      // 界面显示更新.(合同名称,合同金额,价税合计,价税合计大写)
      mContractBillEt.setTextContent(mReceiptDetail.getContractBillName());// 显示不同名称
      mContractAccountEt.setTextContent(mReceiptDetail.getContractAmount() + "");
      mTaxTotalEt.setText(NumberUtil.numberBigToString(mReceiptDetail.getMakedInvoiceAmount()));
      mTaxTotalCapEt.setText(
          NumberUtil.number2CNMontrayUnit(mReceiptDetail.getMakedInvoiceAmount()));
      enableTaxTotal();
      // 主记录id,合同订单id,合同订单类型.用于动态生成子表.

      SharedPreferencesUtil.setString(getActivity(), SharedPreferencesUtil.RECEIPT_CONTRACT_ID,
          mReceiptDetail.getContractBillId());
      SharedPreferencesUtil.setString(getActivity(), SharedPreferencesUtil.RECEIPT_CONTRACT_TYPE,
          mReceiptDetail.getOrderType());
    }
    if (requestCode == REQUEST_RECEIPT_PERSON) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);

      //mExcManId = customer.getId();// 执行人工号
      mReceiptPersonEt.setTextContent(customer.getName());
      mReceiptDetail.setInvoiceMaker(customer.getName());// 执行人姓名
      mReceiptDetail.setInvoiceMakerCode(customer.getId());//工号jobno.
    }
    if (requestCode == REQUEST_RECEIVE_PERSON) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);

      etReceivePersonReceiptInfo.setTextContent(customer.getName());
      mReceiptDetail.setInvoiceReciverName(customer.getName());// 执行人姓名
      mReceiptDetail.setInvoiceReciverCode(customer.getId());//工号jobno.
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   * 设置 价税合计是否可编辑
   */

  private void enableTaxTotal() {
    // 只有合同订单单选可修改价税合计.
    if (mReceiptDetail != null
        && mReceiptDetail.getContractBillName() != null
        && !mReceiptDetail.getContractBillName().contains(",")) {
      mTaxTotalEt.setEnabled(true);
    } else {
      mTaxTotalEt.setEnabled(false);
    }
  }

  /**
   * 当子表保存后,更新主表的销项税和销项额为子表累加所得.
   */
  public void updateSalesTaxMoney(Double salestax, Double salesMoney, Double sumMoney) {
    // 更新数据
    // 更新界面.
    mSalesTaxEt.setTextContent(NumberUtil.numberBigToString(salestax));//销项税
    mReceiptDetail.setOutputTax(salestax);
    mReceiptDetail.setMtsumPrice(salesMoney);//销项额(不含税)
    mSalesMoneyEt.setTextContent(NumberUtil.numberBigToString(salesMoney));
    mReceiptDetail.setMakedInvoiceAmount(sumMoney);//价税合计(含税)
    mTaxTotalEt.setText(NumberUtil.numberBigToString(sumMoney));

    volleyPostInvoiceUnique(SAVE);
  }

  //    public interface Callbacks {
  //        void skip();
  //    }
}
